package tom.oauth2.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.TokenStore;

/**
 * 资源服务器
 * @author ZHUFEIFEI
 */
@Configuration
@EnableResourceServer
public class MyResourceServerConfig extends ResourceServerConfigurerAdapter {

    private static final String DEMO_RESOURCE_ID = "order";
    @Autowired
    private TokenStore tokenStore;

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        //指定资源id 只有登陆了才能访问
        resources.resourceId(DEMO_RESOURCE_ID).stateless(true);
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
                .and()
                .requestMatchers().anyRequest()
                .and()
                //允许匿名
                .anonymous()
                .and()
                //order 必须登陆授权后才能访问
                .authorizeRequests()
                .antMatchers("/order/**")
                //必须有角色权限
                .hasAuthority("admin_role");
        //自定义未授权返回内容
        http.exceptionHandling().authenticationEntryPoint(new CustomAuthenticationEntryPoint());
        //注销允许任何人访问，并且增加注销成功后的处理器
        http.logout().logoutSuccessHandler(new CustomLogoutSuccessHandler(this.tokenStore)).permitAll();
        //授权码对外开放
        http.authorizeRequests().antMatchers("/oauth/authorize").permitAll();
    }
}
